<template>
  <Modal v-model:visible="isShow" :title="t('home_page_custom_avatar')" :zindex="1000">
    <div class="popup_body">
      <div class="form_card">
        <div class="form_container vertical">
          <div class="body vertical center">
            <!-- 表格 -->
            <div class="table_box">
              <div class="list_item" v-for="(item, index) in dataList" :key="index">
                <img class="img" :key="item.value" v-lazy="`/imgs/head_icons/${item.value}.webp`"
                  @click="clickTab(item)" />
                <iconpark-icon v-if="curTab == item.value" class="item_icon" name="gou-f4melk0d"></iconpark-icon>
              </div>
              <div @click="clickTab({ value: userAvatar })" class="list_item" style="position: relative"
                v-if="userAvatar">
                <img class="img" :key="userAvatar" v-lazy="joinURL(settings.media_url, userAvatar)" alt="" />
                <iconpark-icon v-if="curTab == userAvatar" class="item_icon" name="gou-f4melk0d"></iconpark-icon>
                <iconpark-icon @click.stop="curTab = dataList[0].value, userAvatar = ''" name="exit" style="
                    position: absolute;
                    right: -6px;
                    top: -2px;
                    border: 1px solid #fff;
                    border-radius: 50%;
                    padding: 1px;
                  "></iconpark-icon>
              </div>
              <div class="list_item" v-else>
                <div class="img" style="border: none">
                  <iconpark-icon style="
                      font-size: 46px;
                      opacity: 0.4;
                      position: absolute;
                      top: 50%;
                      left: 50%;
                      transform: translateX(-50%) translateY(-50%);
                    " name="more"></iconpark-icon>
                  <div style="
                      height: 18px;
                      padding: 0 4px;
                      display: flex;
                      align-items: center;
                      justify-content: center;
                      border-radius: 15px;
                      border: 1px solid #434265;
                      position: absolute;
                      bottom: -6px;
                      left: 50%;
                      transform: translateX(-50%);
                      color: #c6c4f5;
                      font-size: 10px;
                      font-weight: 400;
                      white-space: nowrap;
                      background-color: #06071f;
                    ">
                    {{ t("home_page_custom_avatar2") }}
                  </div>
                </div>

                <nut-uploader style="
                    opacity: 0;
                    position: absolute;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                  " accept=".jpg,.jpeg,.png" :before-xhr-upload="beforeUpload" @delete="(e: any) => {
                    removeImg(e);
                  }
                  "></nut-uploader>
              </div>
            </div>
          </div>
        </div>

        <div style="text-align: center;margin-top: 8px;">{{ t('home_page_avatar_tip2') }}</div>
      </div>

      <div class="submit_btn">
        <Btn style="background: #282747 !important" height="44px"  @click="isShow = false"
          class="submit btn">
          {{ t("cancel") }}</Btn>
        <Btn height="44px"  @click="submitAction" class="submit btn">{{
          t("save")
        }}</Btn>
      </div>
    </div>
  </Modal>
</template>

<script setup lang="ts">
import { computed, ref, watch, defineAsyncComponent } from "vue";
import { useI18n } from "vue-i18n";
import { storeToRefs } from "pinia";
import { User } from "@/store/user.ts";
import { Page } from "@/store/page.ts";
import pinia from "@/store";
import { showNotify } from "@nutui/nutui";
import PKwebsocket from "@/lolo/Ws";
import { NetPacket } from "@/netBase/NetPacket";
import { joinURL } from '@/utils/publicMethods'
import CryptoJS from "crypto-js"

const Modal = defineAsyncComponent(() => import("@/components/Modal.vue"));
const Btn = defineAsyncComponent(() => import("@/components/Btn.vue"));
const { t } = useI18n();
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});
const UserStore = User(pinia);
const PageStore = Page(pinia);
const emit = defineEmits(["update:visible", "change"]);
const { roleInfo } = storeToRefs(UserStore);
const { settings } = storeToRefs(PageStore);

const curTab: any = ref(roleInfo.value.head_photo);
if (!curTab.value) {
  curTab.value = '1002'
}
const userAvatar: any = ref("");
watch(props, (val) => {
  if (val.visible) {
    curTab.value = roleInfo.value.head_photo;
    if (roleInfo.value.head_photo && roleInfo.value.head_photo.toString().includes(".")) {
      userAvatar.value = roleInfo.value.head_photo;
    }
  } else {
    userAvatar.value = ''
  }
});
const dataList: any = ref([
  // { value: '1001' },
  { value: "1002" },
  { value: "1003" },
  { value: "1004" },
  { value: "1005" },
  // { value: '1006' },
  // { value: '1007' },
  { value: "2003" },
  { value: "2004" },
  { value: "2005" },
  { value: "2006" },
  // { value: '1012' },
]);

const isShow = computed({
  get: function () {
    return props.visible;
  },
  set: function (value) {
    emit("update:visible", value);
  },
});

const clickTab = (e: any) => {
  // console.log('*****', e)
  curTab.value = e.value;
};
const submitAction = () => {
  if (!curTab.value) return emit("update:visible", false);
  const query = NetPacket.req_select_head_icon();
  query.new_head_icon = curTab.value;
  PKwebsocket.instance.send(query, true, {
    callbackName: 'msg_notify_select_head_icon_result',
    callback: resultHandle
  })
};

// 生成签名
const generateSignature = (apiKey: string, secretKey: string) => {
  const timestamp = Math.floor(Date.now() / 1000);
  const message = `API-KEY=${apiKey}&TIMESTAMP=${timestamp}`;
  const signature = CryptoJS.HmacSHA256(message, secretKey).toString();

  return { signature, timestamp };
}
// 上传图片
const beforeUpload = (_xhr: any, data: any) => {
  const file = data.sourceFile;

  if (file && file.size > 1024 * 1024 * 10) {
    // 10MB限制
    showNotify.danger(t('home_page_avatar_tip'));
    return;
  }
  const apiKey: any = 'GZ4M8F7X2Q9L1YV5K3C6WAB0T';
  const secretKey = 'KJ7NQW5X1M9P3L8V2Y4Z6AC0BDFGTRHS';
  const {signature, timestamp}: any = generateSignature(apiKey, secretKey)

  const formData = new FormData();
  formData.append("role_id", `${roleInfo.value.id}`);
  formData.append("image", file);
  formData.append("device_id", `${roleInfo.value.id}`);
  formData.append("dir_path", '/avatar');
  formData.append("from", 'frontend');
  fetch(joinURL(settings.value.api_url, `/api/upload/img`), {
    method: "POST",
    headers: {
      'API-KEY': apiKey,
      'SIGNATURE': signature,
      'TIMESTAMP': timestamp,
    },
    body: formData,
  })
    .then((response) => response.json())
    .then((response) => {
      if (response.code == 200 || response.code == "success") {
        const urlImg = response.data.path;
        showNotify.success(t("operation_success"));
        curTab.value = urlImg;
        userAvatar.value = urlImg;
      } else {
        showNotify.danger(response.message);
      }
    });
};
const removeImg = (e: any) => {
  console.log("删除---", e);
};


// 头像信息
const resultHandle = async (rs: any) => {
  if (rs.is_success == 1) {
    // 修改本地缓存
    // roleInfo.value.head_photo = curTab.value;
    // await User(pinia).getRoleInfo(roleInfo.value);
    emit('change')
    emit("update:visible", false);
  } else {
    showNotify.danger("操作失败");
  }
};


</script>
<style lang="scss" scoped>
.popup_body {
  color: #fff;
  padding-bottom: 20px;

  .form_card {
    padding: 16px 12px;
    height: 180px;

    .form_container {
      border-radius: 8px;
      background: #0d0c24;
      box-shadow: 0.5px 0.5px 1px 0px #212361 inset;
      padding: 16px 8px 0 8px;
    }

    .table_box {
      display: flex;
      flex-wrap: wrap;

      .list_item {
        display: flex;
        font-size: 12px;
        width: 48px;
        height: 48px;
        margin-left: 16px;
        margin-bottom: 16px;
        position: relative;
        text-align: center;
        overflow: visible;

        .item_icon {
          background-color: #fff;
          border-radius: 50%;
          font-size: 16px;
          position: absolute;
          bottom: -6px;
          left: calc(50% - 6px);
          // transform: translateX(-50%);
        }

        &:nth-child(5n + 6),
        &:nth-child(1) {
          margin-left: 0;
        }

        .img {
          cursor: pointer;
          width: 44px;
          height: 44px;
          border: 2px solid #434265;
          border-radius: 50%;

          &.active {
            border-color: #ad95f6;
          }
        }

        :deep(.nut-uploader) {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;

          .nut-uploader__upload {
            background: rgba(0, 0, 0, 0.7);
            border-radius: 10px;
          }

          .nut-uploader__upload,
          .nut-uploader__preview,
          .nut-uploader__preview-img {
            width: 100%;
            height: 100%;
            margin-right: 0;

            .close {
              color: #fff;
            }
          }

          .nut-uploader__preview__progress {
            display: none;
          }
        }
      }
    }
  }

  .submit_btn {
    display: flex;
    justify-content: space-between;
    padding: 0 10px;
    margin-top: 20px;

    .btn {
      flex: 1;
      margin: 0 8px;
    }
  }
}
</style>
